package com.example.base_mvvm.net;

import com.blankj.utilcode.util.SPUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private RetrofitManager() {
    }

    private static RetrofitManager retrofitManager;
    private Retrofit retrofit;

    public static RetrofitManager getInstance(){
        if( retrofitManager == null){
            synchronized (RetrofitManager.class){
                if(retrofitManager == null){
                    retrofitManager = new RetrofitManager();
                }
            }
        }
        return retrofitManager;
    }
    public Retrofit getRetrofit(){
        retrofit = createRetrofit();
        return retrofit;
    }

    private Retrofit createRetrofit() {
//      设置网络请求的参数和数据
        OkHttpClient.Builder client = new OkHttpClient.Builder()
//               设置在规定时间内读取如超时则抛出读取超时异常   TimeUnit.SECONDS意思是设置单位为秒
                .readTimeout(30, TimeUnit.SECONDS) //这里就是30秒
                .writeTimeout(30,TimeUnit.SECONDS)
                .connectTimeout(30,TimeUnit.SECONDS)
//               给所有的网络请求中的Header中添加Token,不需要的位置不用管,需要的位置,会自动读取token
//               每次网络请求中自动添加 token 到请求头，并且可以打印请求和响应的详细信息
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))//这里拦截器作用是获取日志
                .addInterceptor(new Interceptor() {
//               给所有来请求数据的Header都添加一个token
                    @Override
                    public Response intercept(Chain chain) throws IOException {
//                        chain是传递数据 并且调用下一个拦截器
                        String token = SPUtils.getInstance().getString(Const.SP_TOKEN);
                        Request.Builder newBuilder = chain.request().newBuilder();//newBuilder是构建器
                        newBuilder.addHeader(Const.PARAM_TOKEN,token);//将token添加到newBuilder中
                        return chain.proceed(newBuilder.build());//返回最终响应结果
                    }
                });
        Retrofit.Builder retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//将retrofit中的接口信息转换为Rxjava的Observable(被观察者)对象,目的是异步处理数据流
                .addConverterFactory(GsonConverterFactory.create())//json转java
                .client(client.build())
                .baseUrl(Const.URL);
        return retrofit.build();
    }

}
